<template>
  <el-container>
    <el-header>
      <h1>商品管理</h1>
    </el-header>
    <div style="display: flex ;margin-left: 500px">
      <el-input v-model="input" style="width: 240px" placeholder="请输入商品" />
      <el-button :disabled="input.length===0" @click='setInfo'  type="primary">搜索</el-button>
      <el-button @click="addProduct" style="width: 100px;margin-left: 350px" type="info">添加商品</el-button></div>
    <el-main>
      <el-table :data="product" style="width: 100%" >
        <el-table-column prop="name" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="productModel.images" label="商品图片" width="100">
          <template #default="{ row }">
            <img v-if="product[0].id!==0" :src="row.images.split(';')[0]" alt="品牌Logo" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="商品描述" width="400"></el-table-column>
        <el-table-column prop="warrantPeriod" label="商品保修期(年）" width="150"></el-table-column>
        <el-table-column prop="price" label="商品价格" width="100"></el-table-column>
        <el-table-column prop="inventory" label="商品库存" width="100"></el-table-column>
        <el-table-column label="操作" width="150" >
          <template #default="{ row }">
            <el-button :disabled="product[0].id===0" type="primary" size="small" @click="editProduct(row)">编辑</el-button>
            <el-button :disabled="product[0].id===0" type="danger" size="small" @click="deleteProduct(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" title="商品操作" direction="rtl" size="50%">
      <!-- 添加文章表单 -->
      <el-form :model="productModel" label-width="100px">
        <el-form-item label="商品名称"><el-input v-model="productModel.name" style="width: 240px" placeholder="请输入商品名" /></el-form-item>
        <el-form-item label="商品品牌"><el-input v-model="brandName" style="width: 240px" placeholder="请输入商品品牌" /></el-form-item>
        <el-form-item label="商品类型">
          <el-select v-model="productModel.type" placeholder="Select" style="width: 240px">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" >
          <el-upload
              class="avatar-uploader"
              :auto-upload="true"
              :v-model="productModel.images.split(';')[num++]"
              action="http://localhost:8080/upload" name="file" :headers="{'Authorization':tokenStore.token.data}"
              list-type="picture-card"
              :on-success="uploadSuccess"
              :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品简述">
          <div class="editor">
            <el-input
                v-model="productModel.content"
                style="width: 300px"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入品牌内容"
            />
          </div>
        </el-form-item>
        <el-form-item label="保修期">
          <div class="editor">
            <el-slider style="width: 600px" v-model="productModel.warrantPeriod" :step="10" :format-tooltip="formatTooltip"/>
          </div>
        </el-form-item>
        <el-form-item label="价格">
          <div class="editor">
            <el-input-number v-model="productModel.price" :min="1" :max="100000"  />
          </div>
        </el-form-item>
        <el-form-item label="库存">
          <div class="editor">
            <el-input-number v-model="productModel.inventory" :min="1" :max="10000" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tokeProduct">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-container>
</template>

<script setup>

import {ref} from "vue";
import {useTokenSotre} from "@/stores/token";
import {ElMessage, ElMessageBox} from "element-plus";
const tokenStore = useTokenSotre()
const num = ref(0)
import {deletePicture} from '@/api/picture'
const handleRemove = (uploadFile, uploadFiles) => {
  deletePicture(uploadFile)
  console.log(uploadFile)
  productModel.value.images.split(';')[num]=''
  productModel.value.images=productModel.value.images.slice(0, -1);
}
const options = [
  {
    value: 0,
    label: 'cpu',
  },
  {
    value: 1,
    label: 'gpu',
  },
  {
    value: 2,
    label: '主板',
  },
  {
    value: 3,
    label: '内存条',
  },
  {
    value: 4,
    label: '硬盘',
  },
  {
    value: 5,
    label: '电源',
  },
  {
    value: 6,
    label: 'cpu散热器',
  },
  {
    value: 7,
    label: '机箱',
  },
  {
    value: 8,
    label: '显示器',
  },
]
//上传成功的回调函数
const uploadSuccess=(result)=>{
  if (productModel.value.images!==''){
    productModel.value.images =productModel.value.images+';'+ result.data
  }else {
    productModel.value.images =result.data
  }
  console.log(result.data)
}

const brandName = ref('')
const product = ref([
  {
    id:0,
    name:'',
    type:'',
    brandId:'',
    images: '',
    content:'',
    warrantPeriod:'',
    price:'',
    inventory:'',
    brandName:''
  },
],)


const formatTooltip = (val) => {
  return val / 10
}
const editProduct = (row)=>{
  drawer.value=1
  visibleDrawer.value=true
  productModel.value.name=product.value[0].name
  productModel.value.images=product.value[0].images
  productModel.value.type=product.value[0].type
  productModel.value.brandId=product.value[0].brandName
  productModel.value.content=product.value[0].content
  productModel.value.warrantPeriod=product.value[0].warrantPeriod*10
  productModel.value.price=product.value[0].price
  productModel.value.inventory=product.value[0].inventory
  num.value = 0
  fix.value=0
}
//编辑品牌

const input=ref('')
//添加品牌
const addProduct = ()=>{
  drawer.value=0
  visibleDrawer.value=true
  clearInfo()
}
const clearInfo=()=>{
  productModel.value.name=''
  productModel.value.images=''
  productModel.value.type=''
  productModel.value.brandId=''
  productModel.value.content=''
  productModel.value.warrantPeriod=''
  productModel.value.price=''
  productModel.value.inventory=''
  num.value=0
}
const drawer = ref(0)
//删除分类
const deleteProduct=(row)=>{
  ElMessageBox.confirm(
      '请问您确定要删除吗',
      '提醒',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await deleteProductService(row.id)
        clearInfo()
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
//控制抽屉是否显示
const visibleDrawer = ref(false)

const productModel = ref({
  id:'',
  name:'s',
  type:0,
  brandId:0,
  images: '',
  content:'',
  warrantPeriod:'',
  price:'',
  inventory:'',
  heat:11
})


import {deleteProductService, productInsertService, upProductInfoService} from '@/api/product'
const fix = ref(1)
const tokeProduct = async ()=>{
  if (fix.value===1){
    let result = await brandInfoService(brandName.value)
    if (result.data){
      productModel.value.brandId = result.data.id
      await productInsertService(productModel.value)
      ElMessage.success("添加成功")
      visibleDrawer.value=false
      clearInfo()
    }else {
      ElMessage.success("品牌输入有误")
    }
  }else {
    await updateInfo()
  }
}


import {productInfoByNameService} from '@/api/product'
import {Plus} from "@element-plus/icons-vue";
import {brandIdInfoService, brandInfoService} from "@/api/brand";
import {UploadUserFile} from "element-plus";
const setInfo=async ()=>{
  let result =await productInfoByNameService(input.value)
  console.log(result.data)
  product.value = result.data
  for (let i = 0;i<product.value.length;i++){
    product.value[i].brandName = getBrand(product.value[i].brandId)
    product.value[i].warrantPeriod = product.value[i].warrantPeriod/10
  }

}
const getBrand=async (row)=>{
  let result =await brandIdInfoService(row)
  return result.data
}
const updateInfo=async ()=>{
  let result = await brandInfoService(brandName)
  if(result.data){
    productModel.value.id = result.data.id
    await upProductInfoService(productModel.value)
    ElMessage.success("修改成功")
    visibleDrawer.value=false
    clearInfo()
  }else {
    ElMessage.success("品牌输入有误")
  }

}


</script>